package com.batchengine.system;

import static com.batchengine.BatchEngine.getEngine;
import static com.batchengine.Definitions.OperationType.RESTART_POOL;
import static com.batchengine.Definitions.OperationType.STOP_POOL;
import com.batchengine.manager.WorkerManager;
import com.batchengine.pool.WorkerPool;
import static com.batchengine.system.SystemJobs.getSystemJobFeeder;
import com.batchengine.task.DefaultTask;
import com.batchengine.task.TaskContext;
import com.batchengine.task.TaskMode;

import java.util.Map;

/**
 * Created by sunil.incubator@yahoo.com.
 * User: sunil.kalva
 * Date: Aug 13, 2009
 */

/**
 * This class will take up all the offline jobs for stopping and restarting the pools
 */
public class SystemTask extends DefaultTask {

    public SystemTask() {
        super("SystemTask");
    }

    protected SystemTask(String name) {
        super(name);
    }

    @Override
    public void execute(TaskContext context) {

        SystemJobs.WorkerTask workerTask = getSystemJobFeeder().getNextPoolForStop();
        if (null == workerTask || null == workerTask.getManagerId() || null == workerTask.getPoolId()) {
            return;
        }

        Map<Integer, WorkerManager> tasks = getEngine().getManagers();
        WorkerManager taskManger = null;
        try {
            taskManger = tasks.get(workerTask.getManagerId().intValue());
        } catch (Exception e) {
            e.printStackTrace();
        }

        WorkerPool poolToWork = null;
        for (WorkerPool pool : taskManger.getNumberOfActivePools()) {
            if (workerTask.getPoolId() == pool.getPoolId().longValue()) {
                poolToWork = pool;
                break;
            }
        }

        if (null == poolToWork) {
            return;
        }

        if (STOP_POOL.equals(workerTask.getOperationType())) {
            poolToWork.killPool();
        } else if (RESTART_POOL.equals(workerTask.getOperationType())) {
            poolToWork.restartPool();
        }
    }

    @Override
    public TaskMode getTaskMode() {
        return TaskMode.READ;
    }
}
